<?php

/**
 * 前台 首页 模块 Model
 * ============================================================================
 * TBlog TBlog博客系统　BY Tmac PHP MVC framework
 * $Author: zwt007 $  <zwttmac@qq.com>
 * $Id: index.class.php 39 2011-07-11 17:12:35Z zwt007 $
 * http://www.t-mac.org；
 */
class index extends Model
{

    private $article_table;
    private $link_table;
    private $users_table;
    private $category_table;
    private $add_category_table;
    private $ad_table;

    /**
     * 初始化变量　定义私有变量
     */
    public function _init()
    {
        //连接数据库
        $this->connect();
        $this->article_table = '#@__article';
        $this->link_table = '#@__links';
        $this->users_table = '#@__users';
        $this->category_table = '#@__category';
        $this->add_category_table = '#@__addoncategory';
        $this->ad_table = '#@__ad';
    }

    public function getCommon($userinfo)
    {
        $username = $this->H($this->getParam('username'));

        //取config配置文件
        $configcache = Tmac::config('configcache.config', 'admin', '.inc.php');
        $configcache['cfg_powerby'] = $this->HD($configcache['cfg_powerby']);
        //用下面的用户数组
        $user_array = $this->getUser();
        //地方首页上面广告柆
        $this->ShowAD($userinfo['uid'], 'index_top_1');
        $this->ShowAD($userinfo['uid'], 'index_2_left');
        $this->ShowAD($userinfo['uid'], 'index_2_right');
        $this->ShowAD($userinfo['uid'], 'index_3_left');
        $this->ShowAD($userinfo['uid'], 'index_3_right');
        //首页焦点图
        $index_banner_array = $this->ShowAdMore($userinfo['uid'], 'index_banner');

        $this->assign('user_array', $user_array);
        $this->assign('config', $configcache);
        $this->assign('uid', $userinfo['uid']);
        $this->assign('username', $username);
        $this->assign('qq_server', $userinfo['qq_server']);
        $this->assign('index_banner_array', $index_banner_array);
        return $configcache;
    }

    /**
     * 取所有地方站
     * @param type $limit
     * @return type 
     */
    public function getUser($limit = 0)
    {
        $sql = "SELECT uid, username, nicename, url FROM $this->users_table WHERE rank = 2 AND state=1 ORDER BY user_order DESC, uid ASC";
        if (!empty($limit)) {
            $sql .= " LIMIT 0, $limit";
        }
        $rs = $this->db->cacheGetAll($sql, 864000);

        return $rs;
    }

    /**
     * 取首页栏目
     * @param type $limit
     * @return type 
     */
    public function getIndexCategory($limit =0)
    {
        $sql = "SELECT cat_id, cat_name FROM $this->category_table WHERE cat_type = 1";
        if (!empty($limit)) {
            $sql .= " LIMIT 0, $limit";
        }
        $sql .= " ORDER BY cat_order DESC, cat_id ASC";
        $rs = $this->db->getAll($sql, 864000);
        return $rs;
    }

    /**
     * 取首页category info
     * @param type $cid
     * @return type 
     */
    public function getIndexCategoryInfo($cid)
    {
        $sql = "SELECT cat_name, category_keywords, category_description, category_content, urlfile FROM $this->category_table WHERE cat_id = $cid LIMIT 0,1";
        $rs = $this->db->getRow($sql);
        if ($rs) {
            $rs['category_content'] = str_replace('Public/uploadfiles/', STATIC_URL . 'Public/uploadfiles/', $rs['category_content']);
        }
        return $rs;
    }

    /**
     * 取友情链接
     * @param <type> $type
     * @param <type> $name
     * @param <type> $limit
     * @return <type>
     */
    public function getlink($uid, $type = 'img', $name = 'link_img_array', $limit = 8)
    {
        $time = time();
        $sql = "SELECT * FROM $this->link_table ";
        $sql .= "WHERE IF(link_state_radio = 1, link_starttime<$time AND link_endtime>$time, link_state_radio <> 3) ";
        if ($type == 'img') {
            $sql .= " AND link_type_radio <> 1 ";
        } else {
            $sql .= " AND link_type_radio = 1 ";
        }
        if (!empty($uid))
            $sql .= " AND uid = $uid ";
        $sql .= "ORDER BY link_order DESC ";
        if ($limit > 0)
            $sql .= "LIMIT 0, $limit";
        $rs = $this->db->cacheGetAll($sql, 864000);
        if ($type == 'img') {   //如果是图片类型的友链
            foreach ($rs AS $k => $v) {
                if ($v['link_type_radio'] == 3) {
                    $rs[$k]['img'] = $v['link_image'];
                } else {
                    $rs[$k]['img'] = $v['link_image'];
                }
            }
        }
        $this->assign($name, $rs);
        return $rs;
    }

    /**
     * 取栏目分类
     * @global type $category_list
     * @param type $parent
     * @param type $url
     * @param type $uid
     * @param type $username
     * @param type $indexurl
     * @return type 
     */
    public function getCategoryList($parent, $url, $uid, $username, $indexurl)
    {
        $catetory_array = $this->getCategoryArray($uid);
        global $category_list;
        $category_list = '';
        $category_list = $this->fenlei($catetory_array, $parent, $url, $username, $indexurl);
        $this->assign('category_list', $category_list);
        return $category_list;
    }

    /**
     * 取出所有Category数组
     * @param type $uid
     * @return type 
     */
    public function getCategoryArray($uid)
    {
        $sqltree = "SELECT a.cat_id,a.cat_pid,a.cat_name,a.urlfile,b.cat_name AS cat_name_add, b.cat_pid AS cat_pid_add FROM $this->category_table a LEFT JOIN $this->add_category_table b ON a.cat_id = b.cat_id AND b.uid = {$uid} WHERE a.uid = $uid OR a.uid = 1 ORDER BY cat_order DESC, cat_id ASC";
        $rs = $this->db->getAll($sqltree);
        if (is_array($rs)) {
            foreach ($rs AS $k => $v) {
                $rs[$k]['cat_name'] = empty($v['cat_name_add']) ? $v['cat_name'] : $v['cat_name_add'];
                $rs[$k]['cat_pid'] = empty($v['cat_pid_add']) ? $v['cat_pid'] : $v['cat_pid_add'];
            }
        }
        return $rs;
    }

    /**
     * 取无限分类
     * @global type $category_list
     * @param type $arr
     * @param type $parent
     * @param type $url
     * @param type $username
     * @return string 
     */
    public function fenlei($arr, $parent, $url, $username, $indexurl)
    {
        global $category_list; //定义全局变量 返回值        
        $BASE_V = $indexurl . 'Public/' . APP_NAME . '/';
        $num = count($arr);

        for ($i = 0; $i < $num; $i++) {//循环该层
            if ($i == 0) {
                for ($j = 0; $j < $num; $j++) {
                    if ($arr[$j]['cat_pid'] == $parent) {
                        $category_list .= '<ul>';
                        break;
                    }//有元素的该层开始是输出<ul>，
                }
            }
            if ($arr[$i]['cat_pid'] == $parent) {  //层中符合父级id的元素输出
                if (empty($arr[$i]['urlfile'])) {
                    $url_string = PHP_SELF . "?m=$url&username=" . $username . "&cid=";
                } else {
                    $url_string = PHP_SELF . "?m=" . $arr[$i]['urlfile'] . "&username=" . $username . "&cid=";
                }
                $category_list .= "<li><div class='cate'><img src='{$BASE_V}images/ico_jt.jpg' title='展开/收缩'><a href='" . $url_string . $arr[$i]['cat_id'] . "'>" . $arr[$i]['cat_name'] . "</a></div>";
                $this->fenlei($arr, $arr[$i]['cat_id'], $url, $username, $indexurl);  //递归执行寻找当前元素的子元素，这些子元素<ul><li>当前元素<ul><li>子元素</li></ul></li></ul>
                $category_list .= "</li>";      //该</li>放在fenlei函数后是为了把形成该元素的子元素也要包含在该元素的<li>内
            }
            if ($i == ($num - 1)) {
                for ($j = 0; $j < $num; $j++) {
                    if ($arr[$j]['cat_pid'] == $parent) {
                        $category_list .= "</ul>";
                        break;
                    }//闭合ul
                }
            }
        }
        return $category_list;
    }

    /**
     * 取所有的子ID
     * @global type $son_tree_list
     * @param type $parent
     * @return type 
     */
    public function getSonTreeList($parent, $uid)
    {
        $catetory_array = $this->getCategoryArray($uid);
        global $son_tree_list;
        $son_tree_list = '';
        $cat_ids = $this->son_fenlei($catetory_array, $parent);

        if (empty($cat_ids)) {
            $cat_id_rs = $parent;
        } else {
            $cat_id_rs = $cat_ids . ',' . $parent;
            $cat_id_rs = substr($cat_id_rs, 1);
        }

        return $cat_id_rs;
    }

    /**
     * 取所有的子ID
     * @global type $son_tree_list
     * @param type $arr
     * @param type $parent
     * @return type 
     */
    public function son_fenlei($arr, $parent)
    {
        global $son_tree_list; //定义全局变量 返回值        
        $num = count($arr);

        for ($i = 0; $i < $num; $i++) {//循环该层
            if ($arr[$i]['cat_pid'] == $parent) {  //层中符合父级id的元素输出                   
                $arr_array = $arr[$i];
                $son_tree_list .= ',' . $arr_array['cat_id'];
                $this->son_fenlei($arr, $arr[$i]['cat_id']);  //递归执行寻找当前元素的子元素，这些子元素<ul><li>当前元素<ul><li>子元素</li></ul></li></ul>                
            }
        }

        return $son_tree_list;
    }

    /**
     * 从数据库中读取广告
     * @param <type> $id
     * @param <type> $css
     */
    public function ShowAD($uid, $ad_name)
    {
        $sql = "SELECT * FROM $this->ad_table WHERE ad_name = '$ad_name' AND (uid = $uid OR uid = 1) AND ad_state_radio<>3 ORDER BY ad_order DESC, ad_id DESC LIMIT 0,1";
        $rs = $this->db->cacheGetRow($sql, 60);
        if ($rs) {
            //如果状态是正常 就开始判断开始和结束时间
            if ($rs['ad_state_radio'] == 1) {
                if ($rs['ad_starttime'] > time() || $rs['ad_endtime'] < time()) {
                    $ad_body = null;
                    $this->assign($ad_name, $ad_body);
                    return $ad_body;
                }
            }
            //取config配置文件
            $configcache = Tmac::config('configcache.config', 'admin', '.inc.php');
            switch ($rs['ad_type_radio'])
            {
                case 1:
                    $ad_body = "<a href='{$rs['ad_link']}' target='_blank' title='{$rs['ad_title']}'>{$rs['ad_title']}</a>";
                    break;
                case 2:
                    $ad_body = "<a href='{$rs['ad_link']}' target='_blank' title='{$rs['ad_title']}'><img width='{$rs['ad_width']}' height='{$rs['ad_height']}' src='{$configcache['cfg_indexurl']}{$rs['ad_uploadfile']}' border='0' alt='{$rs['ad_title']}' /></a>";
                    break;
                case 3:
                    $ad_body = "{$rs['ad_externallinks']}";
                    break;
            }
        } else {
            $ad_body = null;
        }

        $this->assign($ad_name, $ad_body);
        return $ad_body;
    }

    /**
     * 取多图广告
     * @param type $uid
     * @param type $ad_name
     * @return string 
     */
    public function ShowAdMore($uid, $ad_name)
    {
        $sql = "SELECT * FROM $this->ad_table WHERE ad_name = '$ad_name' AND uid = $uid AND ad_state_radio<>3 ORDER BY ad_id DESC LIMIT 0,1";
        $rs = $this->db->getRow($sql);
        if ((!$rs) && ($uid != 1)) {
            $sql = "SELECT * FROM $this->ad_table WHERE ad_name = '$ad_name' AND uid = 1 AND ad_state_radio<>3 ORDER BY ad_id DESC LIMIT 0,1";
            $rs = $this->db->getRow($sql);
        }
        if ($rs) {
            //如果状态是正常 就开始判断开始和结束时间
            if ($rs['ad_state_radio'] == 1) {
                if ($rs['ad_starttime'] > time() || $rs['ad_endtime'] < time()) {
                    $ad_body = null;
                    $this->assign($ad_name, $ad_body);
                    return $ad_body;
                }
            }
            //取config配置文件
            $configcache = Tmac::config('configcache.config', 'admin', '.inc.php');
            $indexurl = $configcache['cfg_indexurl'];

            if (!empty($rs['ad_imgurls'])) {
                $result = array();
                $img = $this->getCfgBody('img', $rs['ad_imgurls']);
                $ad_body['imgurl'] = $img[3];
                $ad_body['thumburl'] = $img[2];
                $ad_body['thumbtitle'] = $img[1];
                $ad_body['rs'] = $rs;
            } else {
                $ad_body = null;
            }
        } else {
            $ad_body = null;
        }
        $this->assign($ad_name, $ad_body);
        return $ad_body;
    }

    //取出configbody字段里的值
    public function getCfgBody($value, $configbody)
    {
        preg_match_all('/{' . $value . ' key="(.*)" url="(.*)"}(.*){\/' . $value . '}/isU', $configbody, $result);
        return $result;
    }

}